<template>
  <section class="contianer">
    <el-row type="flex" class="row-bg" justify="space-between">
      <div class="main">
        <h2>发表新攻略</h2>
        <p class="travel-desc">分享你的个人游记，让更多人看到哦！</p>

        <el-form class="search-form-content" ref="form">
          <el-form-item label>
            <el-input v-model="form.title" placeholder="请输入标题"></el-input>
          </el-form-item>
          <!-- client-only》》》富文本框组件只在客户端渲染-->
          <el-form-item>
            <client-only>
              <vue-editor
                v-model="form.content"
                :editorToolbar="customToolbar"
                :useCustomImageHandler="true"
                @image-added="imgUpload"
              ></vue-editor>
            </client-only>
          </el-form-item>
          <el-form-item label="选择城市">
            <el-autocomplete
              v-model="form.city"
              :fetch-suggestions="querySearchAsync"
              :trigger-on-focus="false"
              :highlight-first-item="true"
              placeholder="请搜索游玩城市"
              @select="handleSelect"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item>
            <el-button style="width:100px;" type="primary" @click="publish">发布</el-button>
            <el-button style="width:100px;" type="warning" @click="saveDraft">存为草稿</el-button>
          </el-form-item>
        </el-form>
      </div>
      <TravelAside @showData="showData" />
      <!-- 登录对话框 -->
      <el-dialog :show-close="false" title="请先进行登录" :visible.sync="dialogVisible" width="30%">
        <!-- 内容填充 -->
        <div class="login" style="position:relative;">
          <LoginComponent @DialogClose="DialogClose" />
        </div>
      </el-dialog>
    </el-row>
  </section>
</template>

<script>
import TravelAside from "@/components/post/Travel/TravelAside";
import LoginComponent from "@/components/user/LoginComponent";
export default {
  components: {
    TravelAside,
    LoginComponent,
  },
  data() {
    return {
      // 对话框的显示和隐藏
      dialogVisible: false,
      form: {
        title: "",
        content: "",
        city: null,
      },
      customToolbar: [
        ["bold", "italic", "underline"],
        [{ header: 1 }],
        [{ header: 2 }],
        [{ list: "ordered" }, { list: "bullet" }],
        ["image"],
      ],
    };
  },
  methods: {
    //返回输入建议的方法
    querySearchAsync(value, showList) {
      this.loadCity(value).then((suggestList) => {
        console.log(suggestList);
        if (suggestList.length > 0) {
          this.city = suggestList[0].value;
          showList(suggestList);
        } else {
          showList([
            {
              value: "没有匹配数据",
            },
          ]);
        }
      });
    },
    //目标城市下拉选择时触发
    handleSelect(item) {
      this.form.city = item.value;
    },
    //加载城市
    loadCity(value) {
      return this.$axios({
        url: "/airs/city",
        params: {
          name: value,
        },
      }).then((res) => {
        // console.log(res.data.data);

        // 在建议列表中，显示的需要value属性
        const suggestList = res.data.data.map((city) => {
          return {
            //去除‘市’
            value: city.name.replace(/市$/, ""),
            code: city.sort,
          };
        });
        //过滤掉没有带有城市码的城市
        return suggestList.filter((city) => {
          return city.code;
        });
      });
    },
    // 富文本框图片处理
    // file:选中的图片
    // Editor:当前编辑的实例对象
    // cursorLocation:光标所在的位置
    // resetUploader:上传完图片用来重新初始化上传功能的函数
    imgUpload(File, Editor, cursorLocation, resetUploader) {
      let formdata = new FormData();
      formdata.append("files", File);
      this.$axios({
        url: "/upload",
        method: "post",
        data: formdata,
      }).then((res) => {
        console.log(res);
        // insertEmbed编辑器自带的函数，可以往编辑框中放入内容
        let url = this.$axios.defaults.baseURL + res.data[0].url;
        Editor.insertEmbed(cursorLocation, "image", url);
        resetUploader();
      });
    },
    publish() {
      // 判断是否登陆
      if (!this.$store.state.user.userInfo.token) {
        return (this.dialogVisible = true);
      }

      // console.log(this.form);
      if (!this.form.title) {
        this.$message({
          message: "请输入标题",
          type: "error",
        });
        return;
      }
      if (!this.form.content) {
        this.$message({
          message: "请输入内容",
          type: "error",
        });
        return;
      }
      if (!this.form.city) {
        this.$message({
          message: "请输入城市",
          type: "error",
        });
        return;
      }
      this.$axios({
        url: "/posts",
        method: "post",
        headers: {
          Authorization: "Bearer " + this.$store.state.user.userInfo.token,
        },
        data: this.form,
      }).then((res) => {
        // console.log(res);
        if (res.data.message == "新增成功") {
          this.$message({
            message: "游记发布成功",
            type: "success",
          });
          this.form.title = "";
          this.form.content = "";
          this.form.city = "";
        }
      });
    },
    //存为草稿
    saveDraft() {
      // console.log("存为草稿");
      if (!this.form.title) {
        this.$message({
          message: "请输入标题",
          type: "error",
        });
        return;
      }
      if (!this.form.content) {
        this.$message({
          message: "请输入内容",
          type: "error",
        });
        return;
      }
      if (!this.form.city) {
        this.$message({
          message: "请输入城市",
          type: "error",
        });
        return;
      }
      this.$store.commit("post/addPosts", this.form);
    },
    //点击草稿编辑显示数据
    showData(index) {
      // console.log(111);

      this.form = { ...this.$store.state.post.posts[index] };
    },
    DialogClose() {
      console.log(123456);
      this.$message.success("登录成功，您可以发布文章了");
      this.dialogVisible = false;
    },
  },
};
</script>

<style lang="less" scoped>
.contianer {
  width: 1000px;
  margin: 20px auto;
}
.main {
  width: 750px;
  h2 {
    font-weight: 400;
    font-size: 22px;
    margin-bottom: 10px;
  }
  .travel-desc {
    font-size: 12px;
    color: #999;
    margin-bottom: 10px;
  }
  /deep/.ql-editor {
    min-height: 400px;
  }
}
</style>
